package router

import (
	"apiGateWay/internal/config"
	"apiGateWay/internal/database"
	"apiGateWay/internal/repository"
	"apiGateWay/pkg/logger"
)

// LoadRoutes 加载路由配置（仅从数据库加载）
func LoadRoutes(cfg *config.Config) []config.RouteConfig {
	var routes []config.RouteConfig

	// 必须使用数据库
	if !cfg.Database.Enabled || database.DB == nil {
		logger.Error("数据库未启用或未初始化，无法加载路由")
		return routes
	}

	routeRepo := repository.NewRouteRepository(database.DB)
	dbRoutes, err := routeRepo.GetAll()
	if err != nil {
		logger.Errorf("从数据库加载路由失败: %v", err)
		return routes
	}

	for _, dbRoute := range dbRoutes {
		if !dbRoute.IsEnabled {
			continue // 跳过已禁用的路由
		}
		routes = append(routes, config.RouteConfig{
			Name:        dbRoute.Name,
			Path:        dbRoute.Path,
			Target:      dbRoute.Target,
			Methods:     []string(dbRoute.Methods),
			AuthRequired: dbRoute.AuthRequired,
			RateLimit: config.RateLimitRule{
				Enabled: dbRoute.RateLimitQPS > 0 || dbRoute.RateLimitBurst > 0,
				QPS:     dbRoute.RateLimitQPS,
				Burst:   dbRoute.RateLimitBurst,
			},
		})
	}

	logger.Infof("从数据库加载了 %d 个启用路由", len(routes))
	return routes
}

